package com.gwtapps.multisearch.client.view;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class MultiSearchView extends Composite implements HistoryListener{
	private MultiSearchViewListener listener;
	private VerticalPanel mainPanel = new VerticalPanel();
	private TextBox searchBox = new TextBox();
	private Button submitButton = new Button("Search");
	
	public MultiSearchView( MultiSearchViewListener listener ){
		this.listener = listener;
		initWidget( mainPanel );
		HorizontalPanel searchPanel = new HorizontalPanel();			
		searchPanel.add( searchBox );
		searchPanel.add( submitButton );
		searchBox.addKeyboardListener(new KeyboardListenerAdapter(){
			public void onKeyPress(Widget sender, char keyCode, int modifiers){
				if(keyCode == KEY_ENTER )
					onSearch();
			}
		});
		submitButton.addClickListener(new ClickListener(){
			public void onClick(Widget sender){
				onSearch();
			}
		});

		mainPanel.setStyleName("multiSearchView");
		searchPanel.setStyleName("searchPanel");
		searchBox.setStyleName("searchBox");
		submitButton.setStyleName("submitButton");

		mainPanel.add( searchPanel );	
		mainPanel.setCellHorizontalAlignment( searchPanel, HasHorizontalAlignment.ALIGN_CENTER );


		History.addHistoryListener(this);
	}
	
	private void onSearch(){
		String query = searchBox.getText();
		if( query.length() > 0 )
			History.newItem(query);
	}
	
	public void addSearchResultsView( SearchResultsView view ){
		mainPanel.add( view );
	}
	
	public void onHistoryChanged(String historyToken) {
		listener.onSearch(historyToken);
	}
}
